package com.sz.app.customer.api.logistics;

import com.sz.app.customer.api.logistics.dto.OrdOrderBatchResult;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.constants.CommCodes;
import com.sz.biz.common.constants.MessagesCodes;
import com.sz.biz.logistics.ord.dto.OrdOrderBatchDetailDto;
import com.sz.biz.logistics.ord.dto.OrdOrderBatchDetailResultDto;
import com.sz.biz.logistics.ord.dto.OrdOrderFileDto;
import com.sz.biz.logistics.ord.dto.OrdReadResultDto;
import com.sz.biz.logistics.ord.entity.OrderStatus;
import com.sz.biz.logistics.ord.service.OrdOrderBatchService;
import com.sz.common.base.constants.TemplateConstants;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.constants.SysErrorCodes;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: yanhong.xiao.<br>
 * Date: 2017-11-22 18:40:00.
 */
@RestController
@RequestMapping("/api/v1/order/batches")
@Api(description = " ", tags = "037-005、订单-批量下单")
public class OrdOrderBatchController extends BaseController {

    public static final String TYPE_XLSX = "xlsx";
    @Autowired
    private OrdOrderBatchService ordBatchService;


    @RequestMapping(value = "/template", method = {RequestMethod.GET})
    @ApiOperation(value = "获取模板地址", notes = "获取模板地址<br>权限：", position = 1)
    public void getDownloadUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Resource resource = new ClassPathResource(File.separator + "templates" + File.separator + TemplateConstants.ORD_BATCH_CUS_EXCEL);
        File downloadFile = resource.getFile();
        ServletContext context = request.getServletContext();
        // set content attributes for the response
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setContentLength((int) downloadFile.length());

        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"",
                downloadFile.getName());
        response.setHeader(headerKey, headerValue);
        // Copy the stream to the response's output stream.
        try {
            InputStream myStream = new FileInputStream(downloadFile);
            IOUtils.copy(myStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }


    /**
     * excel 批量下单
     * excel的格式为xlsx
     * excel的大小不超过10M，由nginx控制
     *
     * @param file
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @ApiOperation(value = "批量下单", notes = "-", position = 2)
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResultDto batchOrder(MultipartFile file) throws IOException, InvalidFormatException {
        if (null != file && !file.isEmpty()) {
            String filename = file.getOriginalFilename();
            String[] filenames = filename.split("\\.");
            //判断文件格式
            if (!TYPE_XLSX.equals(filenames[filenames.length - 1].toLowerCase())) {
                throw Exceptions.bizException(SysErrorCodes.ERROR_FILE_ILLEGAL);
            }
            //文件的大小，由nginx控制的，10M
            OrdReadResultDto readResultDto = ordBatchService.readCusExcelFromStream(file.getInputStream());
            ResultDto dto = new ResultDto();
            dto.setErrorCode(0);
            dto.setData(readResultDto);
            return dto;
        } else {
            throw Exceptions.bizException(SysErrorCodes.ERROR_FILE_IS_EMPTY);
        }

    }


    @ApiOperation(value = "列表搜索", notes = "根据指定条件获取数据集合", position = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "batchNumber", value = "批次号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "q", value = "模糊查询参数", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query", defaultValue
                    = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数,max<2000", dataType = "int", paramType = "query",
                    defaultValue = "10"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue =
                    "true"),
            @ApiImplicitParam(name = "verifiedStatus", value = "校验状态", dataType = "boolean", paramType = "query"),
    })
    @RequestMapping(value = "", method = RequestMethod.GET)
    public OrdOrderBatchResult find(@RequestParam(required = false) String q,
                                    @RequestParam String batchNumber,
                                    @RequestParam(required = false, defaultValue = "1") int pageIndex,
                                    @RequestParam(required = false, defaultValue = "10") int pageSize,
                                    @RequestParam(required = false) Boolean verifiedStatus,
                                    @RequestParam(required = false) String sort,
                                    @RequestParam(required = false, defaultValue = "true") Boolean asc
    ) {
        q = StringUtils.replaceSqlPattern(q);
        QueryParams qp = new QueryParams(pageSize, pageIndex, q, sort, asc);
        if (null != verifiedStatus) {
            qp.put("verifiedStatus", verifiedStatus);
        }
        qp.put("batchNumber", batchNumber);
        QResultDto result = ordBatchService.findSearchDtoByParam(qp);
        OrdOrderBatchResult batchResult = new OrdOrderBatchResult();
        batchResult.setBatchNumber(batchNumber);
        batchResult.setData(result.getData());
        batchResult.setPagination(result.getPagination());
        return batchResult;
    }

    /**
     * 根据id查询批量订单详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "根据id查询批量订单详情", notes = "批量订单详情", position = 4)
    public ResultDto findByOrderBatchId(@ApiParam(value = "id", required = true) @PathVariable Integer id) {
        OrdOrderBatchDetailResultDto detailResultDto = ordBatchService.getDtoById(id);
        ResultDto resultDto = new ResultDto();
        resultDto.setData(detailResultDto);
        return resultDto;
    }


    /**
     * 修改，修改批量订单的数据
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    @ApiOperation(value = "修改批量订单的数据", notes = "修改批量订单的数据<br>权限：", position = 5)
    public ResultDto update(@RequestBody @Validated OrdOrderBatchDetailDto dto, @PathVariable Integer id) {
        dto.setType(CommCodes.CUSTOMER_USER_TYPE);
        dto.setId(id);
        ordBatchService.updateByDto(dto);
        ResultDto result = new ResultDto();
        result.setErrorCode(0);
        result.setMsg("修改成功");
        return result;
    }

    /**
     * 批量保存草稿
     *
     * @param batchNumber
     * @return
     */
    @RequestMapping(value = "/{batchNumber}/draft", method = RequestMethod.POST)
    @ApiOperation(value = "批量保存草稿", notes = "批量保存草稿", position = 6)
    public ResultDto batchSaveDraft(@PathVariable("batchNumber") String batchNumber) {
        ordBatchService.saveBatchOrder(batchNumber, OrderStatus.DRAFT);
        ResultDto result = new ResultDto();
        result.setErrorCode(0);
        result.setMsg("批量保存草稿成功");
        return result;
    }

    /**
     * 批量提交订单
     *
     * @param batchNumber
     * @return
     */
    @RequestMapping(value = "/{batchNumber}/commit", method = RequestMethod.POST)
    @ApiOperation(value = "批量提交订单", notes = "批量提交订单", position = 6)
    public ResultDto batchCommit(@PathVariable("batchNumber") String batchNumber) {
        ordBatchService.saveBatchOrder(batchNumber, OrderStatus.COMMITED);
        ResultDto result = new ResultDto();
        result.setErrorCode(0);
        result.setMsg("批量提交订单成功");
        return result;
    }

    /**
     * 批量删除
     *
     * @param ids 要删除的id集合
     * @return 操作结果
     */
    @ApiOperation(value = "批量删除某个batchnumber下的数据", notes = "批量删除某个batchnumber下的数据", httpMethod = "POST")
    @RequestMapping(value = "/{batchNumber}/deletions", method = {RequestMethod.POST})
    public ResultDto batchDelete(@PathVariable String batchNumber,@RequestBody @ApiParam(value = "要删除的id集合") List<Integer> ids) {
        ordBatchService.batchDeleteByIds(batchNumber,ids);
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_ORDER_BATCH);
        return dto;
    }


    /**
     * 新增附件
     */
    @ApiOperation(value = "新增附件", notes = "新增订单附件<br>：")
    @RequestMapping(value = "/{id}/orderFiles", method = {RequestMethod.POST})
    public ResultDto addOrderFile(@PathVariable Integer id, @RequestBody @ApiParam(value = "要保存的数据", required = true) @Validated OrdOrderFileDto fileDto) {
        fileDto.setCreateUserType(CommCodes.CUSTOMER_USER_TYPE);
        OrdOrderFileDto ordOrderFileDto = ordBatchService.addOrderFile(id, fileDto);
        ResultDto result = new ResultDto();
        result.setErrorCode(0);
        result.setData(ordOrderFileDto);
        result.setMsg("添加附件成功");
        return result;
    }


    /**
     * 异步校验某个订单下，附件名称的唯一性
     */
    @ApiOperation(value = "校验某个批量订单下，附件名称的唯一性", notes = "校验附件名称的唯一性,false表示存在，true表示不存在")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "附件名称", dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/{id}/attatches/name/check", method = {RequestMethod.POST})
    public ResultDto checkName(@PathVariable Integer id, @RequestParam String fileName) {
        fileName = fileName.trim();
        Boolean result = ordBatchService.checkUniqueName(id, fileName);
        ResultDto resultDto = new ResultDto();
        resultDto.setData(!result);
        return resultDto;
    }

    /**
     * 删除订单附件
     *
     * @return
     */
    @ApiOperation(value = "删除订单的附件", notes = "删除订单附件<br>")
    @RequestMapping(value = "/{id}/attatches/delete", method = {RequestMethod.POST})
    public ResultDto deleteOrderFile(@PathVariable Integer id, @RequestParam String fileName) {
        ordBatchService.deleteAttatches(id, fileName);
        return getDeleteSuccessDto(MessagesCodes.MODULE_ORDER_FILE);
    }

    /**
     * 分页获取某个订单的附件
     */
    @ApiOperation(value = "获取某个订单下的附件列表", notes = "获取某个订单下的附件列表")
    @RequestMapping(value = "/{id}/attatches", method = RequestMethod.GET)
    public ResultDto find(@PathVariable Integer id) {
        List<OrdOrderFileDto> fileDtos = ordBatchService.getDtos(id);
        ResultDto resultDto = new ResultDto();
        resultDto.setData(fileDtos);
        return resultDto;

    }


}
